package core

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"go_19/global"
	"go_19/utils"
	"os"
	"path/filepath"
	"runtime"
)

const defaultConfigFile = "config.yaml"

func init() {
	configFile := getConfigFile()
	fmt.Println("loading config.xml path:" + configFile)

	v := viper.New()
	v.SetConfigFile(configFile)
	v.WatchConfig()
	err := v.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	v.WatchConfig()

	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.Name)
		if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
			fmt.Println(err)
			//配置文件修改重新加载 热加载
			v.WatchConfig()
		}
	})
	if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
		fmt.Println(err)
	}
	global.GVA_VP = v
}

func getConfigFile() string {
	configFile := ""
	fmt.Println(runtime.GOOS)
	// 获取当前文件的路径
	if runtime.GOOS == "darwin" {
		_, filename, _, _ := runtime.Caller(0)
		pwd := utils.GetParentDirectory(filepath.Dir(filename))
		fmt.Println(pwd)
		configFile = pwd + string(os.PathSeparator) + defaultConfigFile
		fmt.Println(configFile)
		if !utils.FileExist(configFile) {
			panic("YMAL配置文件不存在" + configFile)
		}
	} else {
		pwd, _ := os.Getwd()
		configFile = pwd + string(os.PathSeparator) + defaultConfigFile
		checkConfTimes := 0
	Loop:
		if !utils.FileExist(configFile) {
			if checkConfTimes > 1 {
				panic("YMAL配置文件不存在" + configFile)
			}
			fmt.Println("YMAL配置文件不存在" + configFile)
			pwd = utils.GetParentDirectory(pwd)
			configFile = pwd + string(os.PathSeparator) + defaultConfigFile
			//fmt.Println(configFile)
			checkConfTimes++
			goto Loop
		}
	}
	return configFile
}
